﻿using DayuCode.Designer.Entity;
using DayuCode.Designer.Model;
using DayuCode.Designer.Service;
using Sunny.UI;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace DayuCode.Designer.Forms
{
    public partial class DataTableControl : UIPanel
    {
        long m_tableId;
        long m_projectId;
        long m_funcId;
        DataTableVO m_tableVO;
        //List<HDataColumn> m_columns;


        public delegate void OnSelectedTableChangeHandler(HDataTable table);

        public event OnSelectedTableChangeHandler OnSelectedTableChange;

        public DataTableControl()
        {
            InitializeComponent();
        }

        public void SetTable(long tableId, long projectId, long funcId)
        {
            this.m_tableId = tableId;
            this.m_projectId = projectId;
            this.m_funcId = funcId;

            if (projectId == 0) throw new Exception("projectId不能为空");

            IList<HDataTable> pdmTables = DataTableHandler.getPdmDataTableNames(m_projectId);
            pdmTables.Insert(0, new HDataTable());
            cmbTableName.DataSource = pdmTables;

            IList<HDataTable> projectTables = DataTableHandler.getProjectDataTables(m_projectId);
            projectTables.Insert(0, new HDataTable());
            cmbForeignTable.DataSource = projectTables;

            changeDataTable(tableId);
        }

        public void SetFuncId(long funcId)
        {
            m_funcId = funcId;           
        }

        private void FormDataTable_Load(object sender, EventArgs e)
        {
        }

        private void changeDataTable(long tableId)
        {
            this.m_tableId = tableId;
            m_tableVO = DataTableHandler.getDataTableVO(m_tableId);
            cmbTableRelationSubtypes.DataSource = m_tableVO.TableRelationSubtypes;

            if (m_tableVO.Table != null)
            {
                HDataTable table = m_tableVO.Table;
                if (!string.IsNullOrEmpty(table.TableRelationSubtype))
                {
                    cmbTableRelationSubtypes.SelectedItem = m_tableVO.TableRelationSubtypes.Find(it => it.Code == table.TableRelationSubtype);
                }

                loadTableAndColumns(table.TableName);

                var tableItem = (cmbTableName.DataSource as List<HDataTable>)
                    .Find(t => string.Equals(t.TableName, table.TableName, StringComparison.CurrentCultureIgnoreCase));
                cmbTableName.SelectedItem = tableItem;
                txtTableCaption.Text = table.TableCaption;
                txtClassName.Text = table.ClassName;
                txtTableAliasName.Text = table.TableAliasName;

                //txtAttachmentTableName.Text = table.AttachmentTableName;
                //txtAttachmentIdColumn.Text = table.AttachmentIdColumn;
                //txtAttachmentNameColumn.Text = table.AttachmentNameColumn;
                //txtAttachmentBusinessIdColumn.Text = table.AttachmentBusinessIdColumn;
                //txtAttachmentOrderColumn.Text = table.AttachmentOrderColumn;

                if ("2".Equals(table.AttachmentType))
                {
                    chkAttchMultiImage.Checked = true;
                }
                else if ("3".Equals(table.AttachmentType))
                {
                    chkAttchFiles.Checked = true;
                }
                else
                {
                    chkNoAttch.Checked = true;
                }


                chkRevision.Checked = table.Recursion == null ? false : (bool)table.Recursion;
                chkUseRowLock.Checked = table.UseRowLock == null ? false : (bool)table.UseRowLock;
                chkUseMasterLock.Checked = table.UseMasterLock == null ? false : (bool)table.UseMasterLock;

                if (cmbIdColumn.DataSource != null)
                {
                    cmbIdColumn.SelectedItem = (cmbIdColumn.DataSource as List<HDataColumn>).Find(col => col.ColumnName.EqualsIgnoreCase(table.IdColumnName));
                }
                if (cmbNameColumn.DataSource != null)
                {
                    cmbNameColumn.SelectedItem = (cmbNameColumn.DataSource as List<HDataColumn>).Find(col => col.ColumnName.EqualsIgnoreCase(table.NameColumnName));
                }
                if (cmbParentIdColumn.DataSource != null)
                {
                    cmbParentIdColumn.SelectedItem = (cmbParentIdColumn.DataSource as List<HDataColumn>).Find(col => col.ColumnName.EqualsIgnoreCase(table.ParentIdColumnName));
                }
                if (cmbOrderColumn.DataSource != null)
                {
                    cmbOrderColumn.SelectedItem = (cmbOrderColumn.DataSource as List<HDataColumn>).Find(col => col.ColumnName.EqualsIgnoreCase(table.OrderColumnName));
                }
                if (cmbForeignColumn.DataSource != null)
                {
                    cmbForeignColumn.SelectedItem = (cmbForeignColumn.DataSource as List<HDataColumn>).Find(col => col.ColumnName.EqualsIgnoreCase(table.FilterColumnName));
                }
                if (cmbForeignTable.DataSource != null)
                {
                    cmbForeignTable.SelectedItem = (cmbForeignTable.DataSource as List<HDataTable>).Find(t => t.Id == table.ForeignTableId);
                }

                if (cmbIdColumn.SelectedItem == null)
                {
                    cmbIdColumn.SelectedItem = (cmbIdColumn.DataSource as List<HDataColumn>).Find(col => ColumnType.KEY_COLUMN.Equals(col.ColumnType));
                }
                if (cmbNameColumn.SelectedItem == null)
                {
                    cmbNameColumn.SelectedItem = (cmbNameColumn.DataSource as List<HDataColumn>).Find(col => ColumnType.NAME_COLUMN.Equals(col.ColumnType));
                }
                if (cmbParentIdColumn.SelectedItem == null)
                {
                    cmbParentIdColumn.SelectedItem = (cmbParentIdColumn.DataSource as List<HDataColumn>).Find(col => ColumnType.PARENT_ID_COLUMN.Equals(col.ColumnType));
                }
                if (cmbOrderColumn.SelectedItem == null)
                {
                    cmbOrderColumn.SelectedItem = (cmbOrderColumn.DataSource as List<HDataColumn>).Find(col => ColumnType.ORDER_COLUMN.Equals(col.ColumnType));
                }
            }
            else
            {
                m_tableVO.Table = new HDataTable();
                m_tableVO.Table.FuncId = m_funcId;
            }
        }

        private void cmbTableName_SelectedIndexChanged(object sender, EventArgs e)
        {
            HDataTable selectTable = cmbTableName.SelectedItem as HDataTable;
            if (selectTable != null)
            {
                txtTableCaption.Text = selectTable.TableCaption;
                txtClassName.Text = selectTable.TableNameAsClassName;

                loadTableAndColumns(selectTable.TableName);
                if(OnSelectedTableChange != null)
                {
                    OnSelectedTableChange(selectTable);
                }
            }
        }

        private void loadTableAndColumns(string tableName)
        {
            HDataTable table = null;
            List<HDataColumn> columns;
            if (!string.IsNullOrEmpty(tableName))
            {
                table = DataTableHandler.getTableWithColumnsByTableName(m_projectId, tableName);
                if(table == null)
                {
                    return;
                }
                columns = table.Columns;
            }
            else
            {
                return;
            }

            chkRevision.Checked = table.Recursion ?? false;
            txtTableAliasName.Text = table.TableAliasName;
            chkUseMasterLock.Checked = table.UseMasterLock ?? false;
            chkUseRowLock.Checked = table.UseRowLock ?? false;

            if ("2".Equals(table.AttachmentType))
            {
                chkAttchMultiImage.Checked = true;
            }
            else if ("3".Equals(table.AttachmentType))
            {
                chkAttchFiles.Checked = true;
            }
            else
            {
                chkNoAttch.Checked = true;
            }

            List<HDataColumn> columns2 = columns.ToList();
            columns2.Insert(0, new HDataColumn());

            cmbIdColumn.SelectedItem = null;
            cmbNameColumn.SelectedItem = null;
            cmbParentIdColumn.SelectedItem = null;
            cmbOrderColumn.SelectedItem = null;
            cmbForeignColumn.SelectedItem = null;

            cmbIdColumn.DataSource = columns.ToList();
            cmbNameColumn.DataSource = columns2.ToList();
            cmbParentIdColumn.DataSource = columns2.ToList();
            cmbOrderColumn.DataSource = columns2.ToList();
            cmbForeignColumn.DataSource = columns2.ToList();

            cmbIdColumn.SelectedItem = (cmbIdColumn.DataSource as List<HDataColumn>).
                Find(col => string.Equals(col.ColumnName, table.IdColumnName, StringComparison.CurrentCultureIgnoreCase));

            cmbNameColumn.SelectedItem = (cmbNameColumn.DataSource as List<HDataColumn>).
                Find(col => string.Equals(col.ColumnName, table.NameColumnName, StringComparison.CurrentCultureIgnoreCase));

            cmbParentIdColumn.SelectedItem = (cmbParentIdColumn.DataSource as List<HDataColumn>).
                Find(col => string.Equals(col.ColumnName, table.ParentIdColumnName, StringComparison.CurrentCultureIgnoreCase));

            cmbOrderColumn.SelectedItem = (cmbOrderColumn.DataSource as List<HDataColumn>).
                Find(col => string.Equals(col.ColumnName, table.OrderColumnName, StringComparison.CurrentCultureIgnoreCase));

            cmbForeignColumn.SelectedItem = (cmbForeignColumn.DataSource as List<HDataColumn>).
                Find(col => string.Equals(col.ColumnName, table.ForeignColumnName, StringComparison.CurrentCultureIgnoreCase));

            cmbForeignTable.SelectedItem = (cmbForeignTable.DataSource as List<HDataTable>).Find(t => t.Id == table.ForeignTableId);

            //if (cmbIdColumn.SelectedItem == null)
            //{
            //    cmbIdColumn.SelectedItem = m_columns.Find(col => ColumnType.KEY_COLUMN.Equals(col.ColumnType));
            //}
            //if (cmbNameColumn.SelectedItem == null)
            //{
            //    cmbNameColumn.SelectedItem = m_columns.Find(col => ColumnType.NAME_COLUMN.Equals(col.ColumnType));
            //}
            //if (cmbParentIdColumn.SelectedItem == null)
            //{
            //    cmbParentIdColumn.SelectedItem = m_columns.Find(col => ColumnType.PARENT_ID_COLUMN.Equals(col.ColumnType));
            //}
            //if (cmbOrderColumn.SelectedItem == null)
            //{
            //    cmbOrderColumn.SelectedItem = m_columns.Find(col => ColumnType.ORDER_COLUMN.Equals(col.ColumnType));
            //}
        }

        public bool checkFormValid()
        {
            var table = cmbTableName.SelectedItem as HDataTable;
            if (table == null || string.IsNullOrEmpty(table.TableName))
            {
                (this.FindForm() as UIForm).ShowErrorTip("必须选择数据表");
                return false;
            }
            if (cmbIdColumn.SelectedItem == null)
            {
                (this.FindForm() as UIForm).ShowErrorTip("必须选择ID字段");
                return false;
            }
            if (string.IsNullOrWhiteSpace(txtTableCaption.Text))
            {
                (this.FindForm() as UIForm).ShowErrorTip("表中文名不能为空");
                return false;
            }
            if (cmbTableRelationSubtypes.SelectedItem == null)
            {
                (this.FindForm() as UIForm).ShowErrorTip("必须选择表关系类型");
                return false;
            }


            HDataColumn parentCol = cmbParentIdColumn.SelectedItem as HDataColumn;

            CodeItem subType = cmbTableRelationSubtypes.SelectedItem as CodeItem;

            if (chkRevision.Checked)
            {
                if (parentCol == null || string.IsNullOrEmpty(parentCol.ColumnName))
                {
                    (this.FindForm() as UIForm).ShowErrorTip("设置为自递归表，必须先设置父字段ID");
                    return false;
                }
            }
            
            HDataColumn foreignColumn = cmbForeignColumn.SelectedItem as HDataColumn;
            if (foreignColumn == null || string.IsNullOrEmpty(foreignColumn.ColumnName))
            {
                if (TableRelationSubtype.SlaveTable.Equals(subType.Code))
                {
                    (this.FindForm() as UIForm).ShowErrorTip("本表是从表，必须设置外键字段（关联主表的字段）");
                    return false;
                }
                if (TableRelationSubtype.LeafTable.Equals(subType.Code))
                {
                    (this.FindForm() as UIForm).ShowErrorTip("本表是叶子表，必须设置外键字段D（关联目录表的字段）");
                    return false;
                }
            }

            if(foreignColumn != null && !string.IsNullOrEmpty(foreignColumn.ColumnName))
            {
                HDataTable foreignTable = cmbForeignTable.SelectedItem as HDataTable;
                if(foreignTable == null || string.IsNullOrEmpty(foreignTable.TableName))
                {
                    (this.FindForm() as UIForm).ShowErrorTip("已经设置了外键字段，必须选择外键表");
                    return false;
                }
            }

            return true;
        }
        public HDataTable saveData()
        {
            HDataTable table = m_tableVO.Table;

            if (!checkFormValid()) { return null; }

            table.TableName = (cmbTableName.SelectedItem as HDataTable).TableName;
            table.TableRelationSubtype = (cmbTableRelationSubtypes.SelectedItem as CodeItem).Code;
            table.TableCaption = txtTableCaption.Text.Trim();
            table.TableAliasName = txtTableAliasName.Text.Trim();
            table.IdColumnName = (cmbIdColumn.SelectedItem as HDataColumn).ColumnName;
            table.ParentIdColumnName = null;
            if(cmbParentIdColumn.SelectedItem != null)
            {
                table.ParentIdColumnName = (cmbParentIdColumn.SelectedItem as HDataColumn).ColumnName;
            }

            table.NameColumnName = null;
            if (cmbNameColumn.SelectedItem != null)
            {
                table.NameColumnName = (cmbNameColumn.SelectedItem as HDataColumn).ColumnName;
            }

            table.OrderColumnName = null;
            if (cmbOrderColumn.SelectedItem != null)
            {
                table.OrderColumnName = (cmbOrderColumn.SelectedItem as HDataColumn).ColumnName;
            }

            table.ForeignColumnName = null;
            if (cmbForeignColumn.SelectedItem != null)
            {
                table.ForeignColumnName = (cmbForeignColumn.SelectedItem as HDataColumn).ColumnName;
            }

            table.ForeignTableId = null;
            HDataTable foreignTable = cmbForeignTable.SelectedItem as HDataTable;
            if (foreignTable != null && !string.IsNullOrEmpty(foreignTable.TableName))
            {
                table.ForeignTableId = foreignTable.Id;
            }

            //table.AttachmentTableName = txtAttachmentTableName.Text.Trim();
            //table.AttachmentIdColumn = txtAttachmentIdColumn.Text.Trim();
            //table.AttachmentNameColumn = txtAttachmentNameColumn.Text.Trim();
            //table.AttachmentBusinessIdColumn = txtAttachmentBusinessIdColumn.Text.Trim();
            //table.AttachmentOrderColumn = txtAttachmentOrderColumn.Text.Trim();

            table.ClassName = txtClassName.Text;
            table.Recursion = chkRevision.Checked;
            table.UseRowLock = chkUseRowLock.Checked;
            table.UseMasterLock = chkUseMasterLock.Checked;

            if (chkAttchMultiImage.Checked)
            {
                table.AttachmentType = "2";
            }
            else if (chkAttchFiles.Checked)
            {
                table.AttachmentType = "3";
            }
            else
            {
                table.AttachmentType = "0";
            }


            if (table.FuncId == null || table.FuncId == 0)
            {
                table.FuncId = m_funcId;
            }
            m_tableVO.Table = DataTableHandler.saveDataTable(table);

            return table;
        }

        public HDataTable DataTable
        {
            get { return m_tableVO == null ? null : m_tableVO.Table; }
        }

        //private void txtAttachmentTableName_Leave(object sender, EventArgs e)
        //{
        //    if (!string.IsNullOrWhiteSpace(txtAttachmentTableName.Text))
        //    {
        //        if (string.IsNullOrWhiteSpace(txtAttachmentIdColumn.Text))
        //        {
        //            txtAttachmentIdColumn.Text = "ID";
        //        }
        //        if (string.IsNullOrWhiteSpace(txtAttachmentNameColumn.Text))
        //        {
        //            txtAttachmentIdColumn.Text = "FILE_NAME";
        //        }
        //        if (string.IsNullOrWhiteSpace(txtAttachmentBusinessIdColumn.Text))
        //        {
        //            txtAttachmentIdColumn.Text = "BIZ_ID";
        //        }
        //        if (string.IsNullOrWhiteSpace(txtAttachmentOrderColumn.Text))
        //        {
        //            txtAttachmentIdColumn.Text = "ORDNUM";
        //        }
        //    }
        //}

        private void cmbTableRelationSubtypes_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void btnUseDefaultAttch_Click(object sender, EventArgs e)
        {
            //txtAttachmentTableName.Text = "T_ATTACH_IDS";
            //txtAttachmentIdColumn.Text = "ID";
            //txtAttachmentIdColumn.Text = "FILE_NAME";
            //txtAttachmentIdColumn.Text = "BIZ_ID";
            //txtAttachmentIdColumn.Text = "ORDNUM";
        }

        private void chkUseMasterLock_CheckedChanged(object sender, EventArgs e)
        {
            if (chkUseMasterLock.Checked)
            {
                HDataColumn col = cmbParentIdColumn.SelectedItem as HDataColumn;
                if(col == null || string.IsNullOrEmpty(col.ColumnName))
                {
                    (this.FindForm() as UIForm).ShowErrorTip("必须先设置父字段ID");
                }
                if (chkUseRowLock.Checked)
                {
                    (this.FindForm() as UIForm).ShowWarningTip("当本表由主表控制锁定时，本表一般不需要设置为记录级锁定");
                }
            }
        }
    }
}
